package com.nexgo.payment.util;

import android.graphics.Bitmap;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.journeyapps.barcodescanner.BarcodeEncoder;

import java.util.Hashtable;

/**
 * Created by wzp on 2018/3/21.
 */

public class ZXingUtil {
    public static Bitmap createQrCodeBitmap(String content, int width, int height) {
        //核心类， 获取ZXing中的二维码生成类QRCodeWriter
        QRCodeWriter writer = new QRCodeWriter();
        //设置信息的编码格式
        Hashtable<EncodeHintType, String> hints = new Hashtable<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        try{
            /**
             * 调用encode方法之后，会将字符串以二维码的形式显示在矩阵当中
             * 通过调用矩阵的get(x, y)来判断出当前点是否有像素
             */
            BitMatrix bitMatrix = writer.encode(content,  BarcodeFormat.QR_CODE, width, height,hints);

            //声明数组用来保存二维码所需要显示颜色值
            int[] pixels = new int[width * height];

            //循环遍历矩阵中所有的像素点，并分配黑白颜色值
            for(int i = 0; i<height; i++){
                for(int j = 0; j<width; j++){
                    if(bitMatrix.get(j, i)){//说明当前点有像素
                        pixels[width * i +j ] = 0x00000000;
                    }else{
                        pixels[width * i +j] = 0xffffffff;
                    }
                }
            }
            //根据填充好的颜色值数组，生成新的二维码Bitmap对象并返回
            Bitmap bitmap = Bitmap.createBitmap(pixels, width,height, Bitmap.Config.RGB_565);

            return bitmap;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public static Bitmap createBitmap(String str){
        Bitmap bitmap = null;
        BitMatrix result = null;
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        try {
            result = multiFormatWriter.encode(str, BarcodeFormat.QR_CODE, 300, 300);
            BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
            bitmap = barcodeEncoder.createBitmap(result);
        } catch (WriterException e){
            e.printStackTrace();
        } catch (IllegalArgumentException iae){ // ?
            return null;
        }
        return bitmap;
    }
}
